import { Component } from "@angular/core";
import { NavController,App,LoadingController,AlertController } from 'ionic-angular';
import { HttpClient,HttpHeaders } from '@angular/common/http'
import { NativeStorage } from '@ionic-native/native-storage';
import { TranslateService } from '@ngx-translate/core';


import { AppConfig } from '../../app/app.config';

import { MoveoutPage } from './moveout/moveout'
import { ReviewPage } from '../review/review';
import { WritePage } from '../review/write/write';
import { CheckPage } from './check/check';
import { PayPage } from '../pay/pay';
import { ProductrentPage } from "../product/rent/rent";
import { ProductservicePage } from "../product/service/service";
import { ProductbuyPage } from "../product/buy/buy";
import { ProductperPage } from "../product/per/per";
@Component({
    selector: 'page-messages',
    templateUrl: 'messages.html',
})
export class MessagesPage {
    list={
        queries:[],
        pendbook:[],
        accebook:[],
        payment:[],
        completed:[],
        system:[]
    }
    type: number;
    userTab: string;
    token: string;
    message = 'user';
    loading:any;
    payPage:any;
    reviewPage = ReviewPage;
    checkPage =CheckPage;
    page = {
        queries:1,
        pendbook:1,
        accebook:1,
        payment:1,
        completed:1,
        system:1,
    }
    check_sign = {
        queries:'',
        pendbook:'',
        accebook:'',
        payment:'',
        completed:'',
    
    }
    check_form = {
        queries:[],
        pendbook:[],
        accebook:[],
        payment:[],
        completed:[],
    }
    url:string
    src:string
    constructor(
        private navCtrl: NavController,
        private app:App,
        private stroge:NativeStorage,
        private http:HttpClient,
        private loadingCtrl:LoadingController,
        private alertCtrl:AlertController,
        private translate: TranslateService
    ) {
        this.userTab = 'queries'
        this.url = AppConfig.getUrl()
        this.src = AppConfig.getMainUrl()
        this.payPage = PayPage
        translate.setDefaultLang('en')
    }
    user:any
    ionViewWillEnter(){
        this.stroge.getItem('lang').then(res=>{
            this.translate.use(res)
        })
        this.stroge.getItem('token').then(token=>{
            this.token = token
            this.loadWait()
            this.http.get(this.url+'user/getInfo?token='+token).subscribe(res=>{
                if(res['code']==101){
                    this.user = res['data']
                }
            })
            this.http.get(this.url+'Contact/index?p=1&limit=5&token='+token).subscribe(res=>{
                if(res['code']==101){
                    this.list.queries=res['data']['rows']
                    this.page.queries = 2;
                }
                this.loading.dismiss()
            })
            this.http.get(this.url+'Message/index?p=1&limit=5&token='+token).subscribe(res=>{
                if(res['code']==101){
                    this.list.system=res['data']['rows']
                    this.page.system = 2;
                }
            })
        })
    }
    _cate(item:number){
        switch(item){
            case 1:
                return 'Rent'
            case 2:
                return 'Buy'
            case 3:
                return 'Rent and day'
            case 4:
                return 'Service'
        }
    }
    _type(item:number){
        switch(item){
            case 1:
                return 'month'
            case 2:
                return 'week'
            case 3:
                return 'day'
        }
    }
    _unit(item:number){
        switch(item){
            case 1:
                return '£'
            case 2:
                return '€'
            case 3:
                return '$'
            case 4:
                return '¥'
        }
    }
    _aunit(item:number){
        switch(item){
            case 1:
                return 'SQ.M'
            case 2:
                return 'SQ.FT'
        }
    }
    _otherArea(num,type){
        switch(type){
            case 1:
                return '('+Math.ceil(num/10.764)+'SQ.FT)'
            case 2:
                return '('+Math.ceil(num*10.764)+'SQ.M)'
        }
    }
    _getDate(timestamp:string){
        let date = new Date(parseInt(timestamp+'000'))
        return date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate()+' '+date.getHours()+':'+date.getMinutes()
    }
    loadWait(){
        this.loading = this.loadingCtrl.create({
            content: 'Please wait...'
        });
        this.loading.present();
    }
    updateCucumber(sign,id){
        if(sign==1){
            let index = this.check_form.queries.indexOf(id);
            if( index < 0 ){
                this.check_form.queries.push(id);
            }else{
                this.check_form.queries.splice(index,1);
            }
        }
        if(sign==2){
            let index = this.check_form.pendbook.indexOf(id);
            if( index < 0 ){
                this.check_form.pendbook.push(id);
            }else{
                this.check_form.pendbook.splice(index,1);
            }
        }
        if(sign==3){
            let index = this.check_form.accebook.indexOf(id);
            if( index < 0 ){
                this.check_form.accebook.push(id);
            }else{
                this.check_form.accebook.splice(index,1);
            }
        }
        if(sign==4){
            let index = this.check_form.payment.indexOf(id);
            if( index < 0 ){
                this.check_form.payment.push(id);
            }else{
                this.check_form.payment.splice(index,1);
            }
        }
        if(sign==5){
            let index = this.check_form.completed.indexOf(id);
            if( index < 0 ){
                this.check_form.completed.push(id);
            }else{
                this.check_form.completed.splice(index,1);
            }
        }
    }
    delCucumber(sign){
        switch(sign){
            case 1:
                this.loadWait()
                this.http.get(this.url+'Contact/delete?ids='+this.check_form.queries.toString()+'&token='+this.token).subscribe(res=>{
                    this.http.get(this.url+'Contact/index?p=1&limit=5&token='+this.token).subscribe(res=>{
                        if(res['code']==101){
                            this.list.queries=res['data']['rows']
                            this.page.queries=2
                        }
                        this.loading.dismiss()
                    })
                })
                
                break;
            case 2:
                break;
            case 3:
                break;
            case 4:
                break;
            case 5:
                this.loadWait()
                this.http.get(this.url+'Cart/delete?ids='+this.check_form.completed.toString()+'&token='+this.token).subscribe(res=>{
                    this.http.get(this.url+'Cart/finished?p=1&limit=5&token='+this.token).subscribe(res=>{
                        if(res['code']==101){
                            this.list.queries=res['data']['rows']
                            this.page.completed=2
                        }
                        this.loading.dismiss()
                    })
                })
                break;
        }
        
    }
    data_act(arr,toarr){
        arr.forEach(element => {
            toarr.push(element)
        });
    }
    doInfinite(infiniteScroll,type:number) {
        switch (type) {
            case 1:
                this.http.get(this.url+'Contact/index?p='+this.page.queries+'&limit=5&token='+this.token).subscribe(res=>{
                    if(res['code']==101){
                        this.data_act(res['data']['rows'],this.list.queries)
                        this.page.queries++
                        infiniteScroll.complete();
                    }else{
                        infiniteScroll.enable(false)
                    }
                })
                break;
            case 2:
                this.http.get(this.url+'Cart/pending?p='+this.page.pendbook+'&limit=5&token='+this.token).subscribe(res=>{
                    if(res['code']==101){
                        this.data_act(res['data']['rows'],this.list.pendbook)
                        this.page.pendbook++
                        infiniteScroll.complete();
                    }else{
                        infiniteScroll.enable(false)
                    }
                })
                break;
            case 3:
                this.http.get(this.url+'Cart/acceptted?p='+this.page.accebook+'&limit=5&token='+this.token).subscribe(res=>{
                    if(res['code']==101){
                        this.data_act(res['data']['rows'],this.list.accebook)
                        this.page.accebook++
                        infiniteScroll.complete();
                    }else{
                        infiniteScroll.enable(false)
                    }
                })
                break;
            case 4:
                this.http.get(this.url+'Cart/paid?p='+this.page.payment+'&limit=5&token='+this.token).subscribe(res=>{
                    if(res['code']==101){
                        this.data_act(res['data']['rows'],this.list.payment)
                        this.page.payment++
                        infiniteScroll.complete();
                    }else{
                        infiniteScroll.enable(false)
                    }
                })
                break;
            case 5:
                this.http.get(this.url+'Cart/finished?p='+this.page.completed+'&limit=5&token='+this.token).subscribe(res=>{
                    if(res['code']==101){
                        this.data_act(res['data']['rows'],this.list.completed)
                        this.page.completed++
                        infiniteScroll.complete();
                    }else{
                        infiniteScroll.enable(false)
                    }
                })
                break;
            case 6:
                this.http.get(this.url+'Message/index?p='+this.page.system+'&limit=5&token='+this.token).subscribe(res=>{
                    if(res['code']==101){
                        this.data_act(res['data']['rows'],this.list.system)
                        this.page.system++
                        infiniteScroll.complete();
                    }else{
                        infiniteScroll.enable(false)
                    }
                })
                break;
        }
    }
    tabSelect(item:string){
        this.userTab = item;
        this.loadWait()
        switch (item) {
            case 'queries':
                this.page.queries=1
                
                this.http.get(this.url+'Contact/index?p=1&limit=5&token='+this.token).subscribe(res=>{
                    if(res['code']==101){
                        this.list.queries=res['data']['rows']
                        this.page.queries++
                    }else{
                        
                    }
                    this.loading.dismiss()
                })
                break;
            case 'pendbook':
                this.page.pendbook=1
                this.http.get(this.url+'Cart/pending?p=1&limit=5&token='+this.token).subscribe(res=>{
                    if(res['code']==101){
                        this.list.pendbook=res['data']['rows']
                        console.log(this.list)
                        this.page.pendbook++
                    }else{
                        
                    }
                    this.loading.dismiss()
                })
                break;
            case 'accebook':
                this.page.accebook=1
                this.http.get(this.url+'Cart/acceptted?p=1&limit=5&token='+this.token).subscribe(res=>{
                    if(res['code']==101){
                        this.list.accebook=res['data']['rows']
                        this.page.accebook++
                    }else{
                        
                    }
                    this.loading.dismiss()
                })
                break;
            case 'payment':
                this.page.payment=1
                this.http.get(this.url+'Cart/paid?p=1&limit=5&token='+this.token).subscribe(res=>{
                    if(res['code']==101){
                        this.list.payment=res['data']['rows']
                        this.page.payment++
                    }else{
                        
                    }
                    this.loading.dismiss()
                })
                break;
            case 'completed':
                this.page.completed=1
                this.http.get(this.url+'Cart/finished?p=1&limit=5&token='+this.token).subscribe(res=>{
                    if(res['code']==101){
                        this.list.completed=res['data']['rows']
                        this.page.completed++
                    }else{
                        
                    }
                    this.loading.dismiss()
                })
                break;
        }
    }
    view(id,act,i,array){
        let t = this
        this.presentConfirm(function(){
            t.http.post(AppConfig.getUrl()+'cart/handlededit?token='+t.token, AppConfig.urlEcode({id:id,handled:act}), { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) })
            .subscribe( res => {
                if(res['code']===101){
                    array[i].handled = act
                }else if(res['code']===202){
                    t.alertb('Error!',res['msg']);
                }
            })
        })
        
    }
    tenant(id,act,i,array){
        let t = this
        this.presentConfirm(function(){
            t.http.post(AppConfig.getUrl()+'cart/bgedit?token='+t.token, AppConfig.urlEcode({id:id,bg_status:act}), { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) })
            .subscribe( res => {
                if(res['code']===101){
                    array[i].bg_status = act
                }else if(res['code']===202){
                    t.alertb('Error!',res['msg']);
                }
            })
        })
    }
    refund(id,act,i,array){
        let t = this
        this.presentConfirm(function(){
            t.http.post(AppConfig.getUrl()+'cart/bgedit?token='+t.token, AppConfig.urlEcode({id:id,bg_status:act}), { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) })
            .subscribe( res => {
                if(res['code']===101){
                    array.splice(i-1,1)
                }else if(res['code']===202){
                    t.alertb('Error!',res['msg']);
                }
            })
        })
    }
    refoud_deposit(id,act,i,array){
        let t = this
        this.presentConfirm(function(){
            t.http.post(AppConfig.getUrl()+'cart/depositedit?token='+t.token, AppConfig.urlEcode({id:id,deposit_status:act}), { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) })
            .subscribe( res => {
                if(res['code']===101){
                    array.splice(i-1,1)
                }else if(res['code']===202){
                    t.alertb('Error!',res['msg']);
                }
            })
        })
    }
    moveout(id,act,i,array){
        this.app.getRootNav().push(MoveoutPage);
        // let t = this
        // this.presentConfirm(function(){
        //     t.http.post(AppConfig.getUrl()+'cart/hedit?token='+t.token, AppConfig.urlEcode({id:id,house_status:act}), { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) })
        //     .subscribe( res => {
        //         if(res['code']===101){
        //             array.splice(i-1,1)
        //         }else if(res['code']===202){
        //             t.alertb('failed!',res['msg']);
        //         }
        //     })
        // })
    }
    moveout_shen(id,act,i,array){
        let alert = this.alertCtrl.create({
            title: 'Please input the following information for tenant check.(Only available to UK residents)',
            inputs: [
              {
                name: 'name',
                placeholder: 'Name'
              },
              {
                name: 'birth',
                placeholder: 'Birthday',
              },
              {
                name: 'email',
                placeholder: 'Email',
              },
              {
                name: 'gender',
                placeholder: 'Gender',
              },
              {
                name: 'nationality',
                placeholder: 'Nationality',
              }
            ],
            buttons: [
              {
                text: 'Cancel',
                role: 'cancel',
                handler: data => {
                  console.log('Cancel clicked');
                }
              },
              {
                text: 'Check',
                handler: data => {
                  if (data) {
                    
                  } else {
                    // invalid login
                    return false;
                  }
                }
              }
            ]
          });
          alert.present();
        
    }
    goto(page,id){
        this.app.getRootNav().push(page,{id:id});
    }
    goReview(item){
        if(item.info.contact){
            this.app.getRootNav().push(ReviewPage,{data:item});
        }else{
            this.app.getRootNav().push(WritePage,{data:item});
        }
    }
    gopay(page,item){
        this.app.getRootNav().push(page,{data:item});
    }
    alertb(title,subTitle){
        let alert = this.alertCtrl.create({
            title: title,
            subTitle: subTitle,
            buttons: ['OK']
        });
        alert.present();
    }
    presentConfirm(f) {
        let alert = this.alertCtrl.create({
          title: 'Confirm the operation?',
          buttons: [
            {
              text: 'Cancel',
              role: 'cancel',
              handler: () => {
                
              }
            },
            {
              text: 'Confirm',
              handler: f()
            }
          ]
        });
        alert.present();
      }
      goDetail(item:any){
        let page
        switch(item.info.cate){
          case 1:
            page = ProductrentPage
            break
          case 2:
            page = ProductbuyPage
            break
          case 3:
            page = ProductperPage
            break
          case 4:
            page = ProductservicePage
            break
        }
        this.app.getRootNav().push(page,{id:item.info.id})
      }
   
}